<?php

namespace application\member\controller;

use application\member\models\point;
use ticky\controller;
use ticky\captcha;

class login extends controller {

    /**
     * 会员登录
     */
    public function index() {
        $siteid = isset($_REQUEST['siteid']) && trim($_REQUEST['siteid']) ? intval($_REQUEST['siteid']) : 1;
        //定义站点id常量
        if (!defined('SITEID')) {
            define('SITEID', $siteid);
        }
        if (isset($_POST['dosubmit'])) {
            captcha::instance()->check_code();
            $username = isset($_POST['username']) && is_username($_POST['username']) ? trim($_POST['username']) : showmsg(L('user_name_format_error'));
            $password = isset($_POST['password']) && is_password($_POST['password']) ? trim($_POST['password']) : showmsg(L('password_format_error'));

            //电子邮箱和用户名两种登录方式
            $where = is_email($username) ? array('email' => $username) : array('username' => $username);
            $data = db('member')->where($where)->find();
            if (!$data) {
                showmsg(L('user_does_not_exist'));
            }
            if ($user['password'] != authcode($password)) {
                showmsg('密码错误！', '/admin/login/index', 3);
            }
            if ($data['status'] == '0') {
                showmsg('用户未通过审核！', 'stop');
            } else if ($data['status'] == '2') {
                showmsg('用户已锁定！', 'stop');
            } else if ($data['status'] == '3') {
                showmsg('用户已被管理员拒绝！', 'stop');
            }
            session('uid', $data['uid']);
            session('username', $data['username']);
            session('groupid', $data['groupid']);
            session('adminid', $data['adminid']);

            $where = '`lastloginip`="' . getip() . '",`lastlogintime`="' . TIMESTAMP . '",`loginnum`=`loginnum`+1';
            db('member')->update($where, array('uid' => $data['uid']));
            point::instance()->point_add('1', 2, 0, $data['uid'], $data['username'], $data['experience']);

            $referer = isset($_POST['referer']) && !empty($_POST['referer']) ? urldecode($_POST['referer']) : url('/member/spacecp/index');
            showmsg(L('login_success'), $referer, 1);
        } else {
            $referer = isset($_GET['referer']) && trim($_GET['referer']) ? urlencode($_GET['referer']) : '';
            $this->assign('referer', $referer);
            $this->assign('title', '会员登录');
            $this->display('login');
        }
    }

}
